import { defineStore } from "pinia";
import {
    createInforTech,
    deleteInforTech,
    fetchAllInforTech,
    updateInforTech,
    fetchInforTechById,
} from "@/api/inforemation/technology";
import type { IInforTech } from "@/api/inforemation/technology";
import { ref } from "vue";

export const useInforTechStore = defineStore("inforTech", () => {
    const techList = ref<IInforTech[]>([]);
    const loading = ref(false);
    const error = ref<string | null>(null);

    // 获取所有特色医疗技术
    const getAllTech = async () => {
        try {
            loading.value = true;
            error.value = null;
            const res = await fetchAllInforTech();
            techList.value = res.data;
            return res.data;
        } catch (err) {
            error.value = "获取特色医疗技术列表失败";
            console.error("获取特色医疗技术列表失败:", err);
            throw err;
        } finally {
            loading.value = false;
        }
    };

    // 新增特色医疗技术
    const addTech = async (data: IInforTech) => {
        try {
            loading.value = true;
            await createInforTech(data);
            await getAllTech();
        } catch (err) {
            console.error("新增特色医疗技术失败:", err);
            throw err;
        } finally {
            loading.value = false;
        }
    };

    // 更新特色医疗技术
    const editTech = async (data: IInforTech) => {
        try {
            loading.value = true;
            await updateInforTech(data);
            await getAllTech();
        } catch (err) {
            console.error("更新特色医疗技术失败:", err);
            throw err;
        } finally {
            loading.value = false;
        }
    };

    // 删除特色医疗技术
    const removeTech = async (id: number | string) => {
        try {
            loading.value = true;
            await deleteInforTech(id);
            await getAllTech();
        } catch (err) {
            console.error("删除特色医疗技术失败:", err);
            throw err;
        } finally {
            loading.value = false;
        }
    };

    // 根据ID获取特色医疗技术
    const getTechById = async (id: number | string) => {
        try {
            loading.value = true;
            error.value = null;
            const res = await fetchInforTechById(id);
            return res.data;
        } catch (err) {
            error.value = "获取特色医疗技术失败";
        }
    };

    return {
        techList,
        loading,
        error,
        getAllTech,
        addTech,
        editTech,
        removeTech,
        getTechById,
    };
});